package org.lagou.edu.logSdk.utils.impl;

import org.lagou.edu.logSdk.types.Diff;
import org.lagou.edu.logSdk.types.OpLogRecord;
import org.lagou.edu.logSdk.types.OpLogType;
import org.lagou.edu.logSdk.io.SendOpLog;
import org.lagou.edu.logSdk.utils.OperationLogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SimpleOperationLogUtils<T> implements OperationLogUtils<T> {

    @Autowired
    private SendOpLog<T> sendOpLog;

    private void sendLog(OpLogRecord<T> logRecord) {
        sendOpLog.send(logRecord);
    }


    @Override
    public void logAdd(T object) throws IllegalAccessException {
        OpLogRecord<T> logRecord = new OpLogRecord<>();
        logRecord.setOpLogType(OpLogType.ADD);
        logRecord.setOpLogValue(object);
        logRecord.setDiff(new Diff<T>(){{
            setOldValue(null);
            setNewValue(object);
        }});

        sendLog(logRecord);
    }

    @Override
    public void logUpdate(T originObject, T newObject) throws IllegalAccessException {
        OpLogRecord<T> logRecord = new OpLogRecord<>();
        logRecord.setOpLogType(OpLogType.UPDATE);
        logRecord.setOpLogValue(newObject);
        logRecord.setDiff(new Diff<T>(){{
            setOldValue(originObject);
            setNewValue(newObject);
        }});

        sendLog(logRecord);
    }

    @Override
    public void logDelete(T object) throws IllegalAccessException {
        OpLogRecord<T> logRecord = new OpLogRecord<>();
        logRecord.setOpLogType(OpLogType.DELETE);
        logRecord.setOpLogValue(object);
        logRecord.setDiff(new Diff<T>(){{
            setOldValue(object);
            setNewValue(null);
        }});

        sendLog(logRecord);
    }
}
